import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularExpression {
	public static String ZH_NUMBER = "[一二两三四五六七八九十]+";

	// 将字符串string中的所有符合expression的字串都替换成replacer
	public static String replace(String string, String expression, String replacer) {
		Pattern p = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(string);
		StringBuffer sb = new StringBuffer();
		boolean result = m.find();
		while (result) {
			m.appendReplacement(sb, replacer);
			result = m.find();
		}
		m.appendTail(sb);
		return sb.toString();
	}

	// 判断string是否match给定的expression
	public static boolean isMatch(String string, String expression) {
		boolean isMatch = Pattern.matches(expression, string);
		return isMatch;
	}

	// 按照split规则分割string字符串
	// 例子： String dataArr[] = split("薪水,职位 姓名;年龄 性别", "[,\\s;]");
	public static String[] split(String string, String expression) {
		String[] dataArr = string.split(expression);
		return dataArr;

	}

	// 抽取出所有符合expression的字符串
	// sample:String string = "dfh123chvjd032dfbhjd234cbhj12";
	// String expression = "(\\d+)";

	public static ArrayList<String> extract(String string, String expression) {
		ArrayList<String> result = new ArrayList<String>();
		Pattern p = Pattern.compile(expression);
		Matcher m = p.matcher(string);
		boolean isFind = m.find();
		while (isFind) {
			result.add(m.group());
			string = string.replace(m.group(), "");
			m = p.matcher(string);
			isFind = m.find();
		}

		return result;
	}

	// 返回命中的词所在的片段
	public static ArrayList<String> extractRange(String string, String expression) {
		ArrayList<String> result = new ArrayList<String>();
		Pattern p = Pattern.compile(expression);
		Matcher m = p.matcher(string);
		boolean isFind = m.find();
		while (isFind) {
			String hit = m.group();
			int index = string.indexOf(hit);
			// 删除已经找到的这个词“买”，不能删除所有的“买”
			string = string.substring(0, index) + string.substring(index + hit.length(), string.length());
			hit = string.substring(string.indexOf(hit), string.indexOf(hit) + 5);
			String pos = POSTool.POSSentence(hit);
			System.out.println("截取:" + hit);
			System.out.println("分词:" + pos);
			result.add(hit);
			string = string.replace(m.group(), "");
			m = p.matcher(string);
			isFind = m.find();
		}

		return result;
	}

	public static void main(String args[]) {
		// //测试抽取函数
		// String string = "dfh123chvjd032dfbhjd234cbhj12";
		// String expression = "(\\d+)";
		// ArrayList<String> results = extract(string, expression);
		// System.out.println(results);

		// 综合测试
		// String fileName = "c:/weibo/test/extracts.txt";
		// String content = FileUtils.readFile(fileName, "utf-8");
		// ArrayList<String> results = extractLocation(content);
		// for (int i = 0; i < results.size(); i++)
		// System.out.println("[" + i + "]:" + results.get(i));

	}
}
